package com.cloud.util;

import com.cloud.config.exception.BusinessException;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.logging.Logger;

/**
 * @author Henry.Song
 * @version 2020/11/25
 * @description HTTP辅助类
 */
public class HttpClientUtil {

    private static final Logger LOG = Logger.getLogger(HttpClientUtil.class.getName());

    public static final String CONNECT_TIMEOUT = "connect_timeout";
    public static final String READ_TIMEOUT = "write_timeout";

    public static void handleRequestParsams(HttpURLConnection conn, Map<String, String> params) {
        if (params != null) {
            for(Map.Entry<String, String> entry : params.entrySet()) {
                if (READ_TIMEOUT.equalsIgnoreCase(entry.getKey())) {
                    conn.setReadTimeout(Integer.getInteger(entry.getValue()).intValue());
                } else if (CONNECT_TIMEOUT.equalsIgnoreCase(entry.getKey())) {
                    conn.setConnectTimeout(Integer.getInteger(entry.getValue()).intValue());
                } else {
                    conn.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }
        }
    }

    public static String doPost(String url,String content, Map<String, String> params){
        HttpURLConnection conn = null;
        BufferedReader reader = null;
        PrintWriter writer = null;
        StringBuffer sbf = new StringBuffer();
        try{
            URL u = new URL(url);
            conn = (HttpURLConnection)u.openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(true);

            // 默认参数
            conn.setRequestMethod("POST");
            conn.setReadTimeout(3000);
            conn.setConnectTimeout(3000);
            conn.setRequestProperty("accept","*/*");
            conn.setRequestProperty("connection","Keep-Alive");
            conn.setRequestProperty("content-Type","application/json");

            LOG.warning("doPost\r\nMethod: POST\r\nContent-Type:application/json\r\n" + "Url:" + url + "\r\nContent:" + content);

            handleRequestParsams(conn, params);

            writer = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(),"UTF-8"));
            writer.print(content);
            writer.flush();

            String readLine = null;
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            while((readLine = reader.readLine())!=null){
                sbf.append(readLine);
            }
            LOG.warning("doPost\r\nResult:" + sbf.toString());

        }catch(Exception e){
            e.printStackTrace();
            //throw new BusinessException("调用算法服务失败", e);
        }finally{
            if(writer!=null){
                writer.close();
            }
            if(reader!=null){
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            conn.disconnect();
        }
        return sbf.toString();
    }

    public static String doGet(String url, Map<String, String> params){
        StringBuffer sbf = new StringBuffer();
        HttpURLConnection conn = null;
        BufferedReader br = null;
        String content = null;
        try{
            URL u = new URL(url);
            conn = (HttpURLConnection)u.openConnection();

            // 默认参数
            conn.setReadTimeout(3000);
            conn.setConnectTimeout(3000);
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");

            handleRequestParsams(conn, params);

            if(conn.getResponseCode()==200){
                br = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
                while((content=br.readLine())!=null){
                    sbf.append(content);
                }
            }
        }catch(Exception e){
            e.printStackTrace();
            throw new BusinessException("请求数据失败");
        }finally{
            if(br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            conn.disconnect();
        }
        return sbf.toString();
    }
}
